/**
 * Created by wenguangjia on 2017/4/21.
 */
/**
 * Created by willem on 2016/12/28.
 */
(function () {
    'use strict';

    angular
        .module('logcenterApp')
        .controller('frameLogController', frameLogController)
    frameLogController.$inject = ['$scope', 'searchService'];
    function frameLogController($scope, fullSearchService) {
        $scope.param={key:null,svc:null,priority:null,keys:null,startTime:getToday00Clock(),endTime:getToday11Clock(),dateValue:null,dateType:"second",type:"EPEA",area:null,partition:null,queryType:"0"};
        $scope.isQuickQuery=true;
        $scope.queryData={true:"精确查找",false:"快速查找"};

        $scope.date_Config = {
            start: "year",
            depth: "minute",
            format: "yyyy-MM-dd HH:mm:ss"
        };

        var array=new Array();//数据源
        var isLoadMore=true;//如果为false则不自动加载
        var requestData="";//requeste参数
        $scope.selectQuery=function(){
            $scope.param.startTime=null;
            $scope.param.queryType=="0"?$scope.isQuickQuery=true:$scope.isQuickQuery=false;
        }
        $scope.query=function(){
            requestData=generate();
            $scope.frameLogGridOptions.dataSource.read();
        };

        $scope.types=[{ename:"EPEA",cname:"应用程序配置履历"},{ename:"EPEB",cname:"批作业维护履历"},{ename:"EPED",cname:"数据分发配置履历"},{ename:"EPEL",cname:"日志配置履历"},{ename:"EPMC",cname:"频道消息配置履历"},{ename:"EPEP",cname:"代码维护履历"},{ename:"EPES",cname:"授权管理"},{ename:"EPEW",cname:"工作流管理、执行履历"},{ename:"EPEX",cname:"电文配置履历"},{ename:"IDK",cname:"IDK履历"}];
        $scope.typeOptions = {
            template: '<span class="k-state-default">{{dataItem.ename}}---{{dataItem.cname}}</span>'
        };
        //绑定字段处理
        $scope.typeOptions.dataSource = new kendo.data.DataSource({
            transport: {
                read: function (e) {
                    e.success($scope.types);
                }
            },
        });

        //generate elasticsearch query template
        function generate(){
            array.length=0;
            var data={
                "query":{
                    "bool":{
                        "must":[],
                        "filter":[
                            {"range":{"priority":{"gte":"3"}}}
                        ]
                    }
                },
                "sort":{
                    "@timestamp":{
                        "order":"desc"
                    }
                },
                "size": 30,
                "from": 0
            };
            var obj=data['query']['bool'];
            if($scope.param.partition!=undefined && $scope.param.partition!=null && $scope.param.partition!=""){
                var arrayObj={"term":{"partition":$scope.param.partition}};
                obj.filter.push(arrayObj);
            }

            if($scope.param.key!=null && $scope.param.key!=""){
                // var arrayObj={"wildcard":{"message":('*'+$scope.param.key+'*').toLowerCase()}};
                var arrayObj = {
                    "query_string": {
                        "query": $scope.param.key,
                        "analyze_wildcard": true
                    }
                };
                obj.must.push(arrayObj);
            }
            if($scope.param.priority!=null && $scope.param.priority!=""){
                var arrayObj={"term":{"priority":$scope.param.priority}};
                obj.filter.push(arrayObj);
            }
            if($scope.param.type!=null && $scope.param.type!=""){
                var arrayObj={"term":{"category":$scope.param.type}};
                obj.filter.push(arrayObj);
            }
            if($scope.param.keys!=null && $scope.param.keys!=""){
                var arrayObj={"query_string":{"fields":["key1","key2","key3","key4","key5"],"query":$scope.param.keys}};
                obj.filter.push(arrayObj);
            }
            if($scope.isQuickQuery){
                if($scope.param.startTime!=null&&$scope.param.endTime==null){
                    var arrayObj={ "range": { "@timestamp":  {"gte" : $scope.param.startTime} } };
                    obj.filter.push(arrayObj);
                }else if($scope.param.startTime==null&&$scope.param.endTime!=null){
                    var arrayObj={ "range": { "@timestamp":  {"lt" : $scope.param.endTime} } };
                    obj.filter.push(arrayObj);
                }else if($scope.param.startTime!=null&&$scope.param.endTime!=null){
                    var arrayObj={ "range": { "@timestamp":  {"gte" : $scope.param.startTime,"lt" : $scope.param.endTime} } };
                    obj.filter.push(arrayObj);

                }
            }else{
                $scope.param.endTime=new Date();
                if($scope.param.dateValue!=null && $scope.param.dateValue!=""){
                    if($scope.param.dateType=="second"){
                        $scope.param.startTime=new Date();
                        $scope.param.startTime.setSeconds($scope.param.startTime.getSeconds()-$scope.param.dateValue);
                        var arrayObj={ "range": { "@timestamp":  {"gte" : $scope.param.startTime,"lt" : $scope.param.endTime} } };
                        obj.filter.push(arrayObj);
                    }else if($scope.param.dateType=="minute"){
                        $scope.param.startTime=new Date();
                        $scope.param.startTime.setMinutes($scope.param.startTime.getMinutes()-$scope.param.dateValue);
                        var arrayObj={ "range": { "@timestamp":  {"gte" : $scope.param.startTime,"lt" : $scope.param.endTime} } };
                        obj.filter.push(arrayObj);
                    }else if($scope.param.dateType=="hour"){
                        $scope.param.startTime=new Date();
                        $scope.param.startTime.setHours($scope.param.startTime.getHours()-$scope.param.dateValue);
                        var arrayObj={ "range": { "@timestamp":  {"gte" : $scope.param.startTime,"lt" : $scope.param.endTime} } };
                        obj.filter.push(arrayObj);
                    }else if($scope.param.dateType=="day"){
                        $scope.param.startTime=new Date();
                        $scope.param.startTime.setHours($scope.param.startTime.getHours()-($scope.param.dateValue*24));
                        var arrayObj={ "range": { "@timestamp":  {"gte" : $scope.param.startTime,"lt" : $scope.param.endTime} } };
                        obj.filter.push(arrayObj);
                    }else if($scope.param.dateType=="week"){
                        $scope.param.startTime=new Date();
                        $scope.param.startTime.setHours($scope.param.startTime.getHours()-($scope.param.dateValue*24*7));
                        var arrayObj={ "range": { "@timestamp":  {"gte" : $scope.param.startTime,"lt" : $scope.param.endTime} } };
                        obj.filter.push(arrayObj);
                    }else if($scope.param.dateType=="month"){
                        $scope.param.startTime=new Date();
                        $scope.param.startTime.setMonth($scope.param.startTime.getMonth()-$scope.param.dateValue);
                        var arrayObj={ "range": { "@timestamp":  {"gte" : $scope.param.startTime,"lt" : $scope.param.endTime} } };
                        obj.filter.push(arrayObj);
                    }else if($scope.param.dateType=="year"){
                        $scope.param.startTime=new Date();
                        $scope.param.startTime.setFullYear($scope.param.startTime.getFullYear()-$scope.param.dateValue);
                        var arrayObj={ "range": { "@timestamp":  {"gte" : $scope.param.startTime,"lt" : $scope.param.endTime} } };
                        obj.filter.push(arrayObj);
                    }
                }else{
                    var arrayObj={ "range": { "@timestamp":  {"lt" : $scope.param.endTime} } };
                    obj.filter.push(arrayObj);
                }
            }

            return data;
        }

        //文档高度
        function getDocumentTop() {
            var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
            if (document.body) {
                bodyScrollTop = document.body.scrollTop;
            }
            if (document.documentElement) {
                documentScrollTop = document.documentElement.scrollTop;
            }
            scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
            return scrollTop;
        }
        //可视窗口高度
        function getWindowHeight() {
            var windowHeight = 0;
            if (document.compatMode == "CSS1Compat") {
                windowHeight = document.documentElement.clientHeight;
            } else {
                windowHeight = document.body.clientHeight;
            }
            return windowHeight;
        }
        //滚动条滚动高度
        function getScrollHeight() {
            var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
            if (document.body) {
                bodyScrollHeight = document.body.scrollHeight;
            }
            if (document.documentElement) {
                documentScrollHeight = document.documentElement.scrollHeight;
            }
            scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
            return scrollHeight;
        }
        window.onscroll = function () {
            //监听事件内容
            if((getDocumentTop() + getWindowHeight() == getScrollHeight())&&isLoadMore){
                //当滚动条到底时,这里是触发内容
                //异步请求数据,局部刷新dom
                //requestData.from+=sourceCount;
                requestData.from+=30;
                $scope.frameLogGridOptions.dataSource.read();
            }
        };

        /**
         * grid
         * @type {*[]}
         */
        var prioritys=[{text:"TRACE",value:"1"},{text:"DEBUG",value:"2"},{text:"INFO",value:"3"},{text:"WARN",value:"4"},{text:"ERROR",value:"5"},{text:"CRITICAL",value:"6"}];
        var columns = [
            {field: "sourceId", hidden:true},
            {field: "partition", title: "分区", width: "80px"},
            {field: "timestamp", title: "生成时间",format:"{0: yyyy-MM-dd HH:mm:ss:fff}", width: "180px"},
            {field: "logmsg", title: "日志消息", width: "300px"},
            {field: "key1", title: "关键字1", width: "100px"},
            {field: "key2", title: "关键字2", width: "100px", hidden:true},
            {field: "key3", title: "关键字3", width: "100px", hidden:true},
            {field: "key4", title: "关键字4", width: "100px", hidden:true},
            {field: "key5", title: "关键字5", width: "100px", hidden:true},
            {field: "priority", title: "级别", width: "80px",values:prioritys, hidden:true},
            {field: "category", title: "类别", width: "150px", hidden:true},
            {field: "interval", title: "间隔时间", width: "150px", hidden:true},
            {field: "pid", title: "进程号", width: "150px", hidden:true},
            {field: "ip", title: "IP地址", width: "150px", hidden:true},
            {field: "mac", title: "MAC地址", width: "150px", hidden:true},
            {field: "username", title: "用户名", width: "100px"},
            {field: "formname", title: "画面名", width: "100px"},
            {field: "svc", title: "服务名", width: "120px"},
            {field: "func", title: "函数名", width: "150px", hidden:true},
        ];
        $scope.frameLogGridOptions={
            selectable: "row",
            scrollable: true,
            sortable: true,
            resizable: true,
            columns: columns,
            columnMenu:true,
        };
        $scope.frameLogModel = kendo.data.Model.define({
            id: "sourceId",
            fields: {
                timestamp: {validation: {required: true}, type: 'date'},
            }
        });
        $scope.frameLogGridOptions.dataSource = new kendo.data.DataSource({
            autoBind: false,
            transport: {
                read: function (e) {
                    var type = getType();
                    fullSearchService.query(requestData,$scope.param.area,type).then(function(resp){
                        console.log(resp);
                        var data=resp.data.hits.hits;
                        data.length==30?isLoadMore=true:isLoadMore=false;
                        //var array=new Array();
                        angular.forEach(data,function(item){
                            item._source.sourceId=item._id;
                            item._source.username=item._source.uid;
                            item._source.timestamp=item._source['@timestamp'];
                            array.push(item._source);
                        });
                        e.success(array);
                    },function(error){
                        e.error(error)
                    });
                },
                parameterMap: function (options, operation) {
                    if (operation !== "read" && options.models) {
                        return {models: kendo.stringify(options.models)};
                    }
                }
            },
            requestStart: function (e) {
                if (requestData=="") {
                    e.preventDefault();
                }
            },
            schema: {
                model: $scope.frameLogModel
            }
        });

        /**
         * 获取索引类型
         */
        function getType(){
            var type = "ep";
            switch($scope.param.type){
                case 'EPES':
                    type = 'epes';
                    break;
                case 'IDK':
                    type = 'idk';
                    break;
                default:
                    break;
            }
            return type;
        }

        /**
         * 分区配置
         * @type {string}
         */
        $scope.partition = '全部';
        var partitionSrc="";
        fullSearchService.getPartition({}).then(
            function(resp){
                partitionSrc=resp.data;
                $scope.partitionSource=toTree(resp.data);
            },function(err){}
        );
        $scope.selectShow=function(item){
            if(item==0){
                $scope.param.area=null;
                $scope.param.partition=null;
                $scope.partition="全部";
            }
            angular.forEach(partitionSrc,function(k){
                if(item.ename==k.ename){
                    $scope.param.area=k.code;
                    $scope.param.partition=k.ename;
                    $scope.partition=item.fname+"-"+item.cname;
                }
            });
            $scope.win.close();
        };

    }

})();

